package cn.wolfcode.crm.shiro;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.service.IRoleService;
import lombok.Setter;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.ArrayList;
import java.util.List;

public class EmployeeRealm extends AuthorizingRealm {


    @Setter
    private IEmployeeService employeeService;
    @Setter
    private IRoleService roleService;
    @Setter
    private IPermissionService permissionService;

    public String getName() {
        return "EmployeeRealm";
    }

    //验证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //1:获取页面传入的用户名
        String username  = (String) token.getPrincipal();

        //2:根据用户名查询数据库
        Employee employee = employeeService.checkName(username);
        if(employee == null){
            return null;
        }
        //3:将数据库中员工数据封装到info对象返回, 进行下一步操作
        return new SimpleAuthenticationInfo(employee, employee.getPassword(), getName());
    }

    //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //1:获取当前登录的用户信息id
        Employee currentEmp = (Employee) principals.getPrimaryPrincipal();

        List<String> roles = null;
        List<String> permissions = null;
        //2:根据用户id获取角色信息跟权限信息
        //判断是否是超级管理员
        if(currentEmp.isAdmin()){
            //拥有所有角色
            List<Role> list = roleService.list();
            roles = new ArrayList<>();
            for (Role role : list) {
                roles.add(role.getSn());
            }
            //权限
            permissions = new ArrayList<>();
            permissions.add("*:*");

        }else{
            roles = roleService.queryRoleSnByEmpId(currentEmp.getId());
            permissions = permissionService.queryPermissionResourceByEmpId(currentEmp.getId());
        }
        //3:将信息封装info对象, 进行下一步操作
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(roles);
        info.addStringPermissions(permissions);
        return info;
    }


}
